class ApplicationController < ActionController::Base
  #protect_from_forgery
  before_filter :get_cart

  def after_sign_in_path_for(resource)
    if resource.role?(:admin)
      admin_root_url
    else
      current_cart.kvn_branch = resource.client.kvn_branch

      if !current_user.role?(:admin) && SavedCart.has_saved_items(current_user.client.id)
        show_cart_url(:show_alert => true)
      else
        root_url
      end
    end
  end

  rescue_from CanCan::AccessDenied do |exception|
    flash[:error] = exception.message
    redirect_to root_url
  end

  def check_if_admin
    if current_user.blank? || !current_user.role?(:admin)
      redirect_to root_url
    else
      true
    end
  end

  def check_if_client
    if current_user.blank? || !current_user.role?(:client)
      redirect_to root_url
    else
      true
    end
  end

  private

  def current_cart
    if !current_user.blank? && !current_user.role?(:admin) && (session[:cart].blank? || !session[:cart].active?)
      session[:cart] = Cart.new(current_user.client.id)
    end

    session[:cart]
  end

  def get_cart
    @cart = current_cart
  end
end
